//
//  YQContactsViewController.swift
//  yq微信
//
//  Created by yq on 2017/8/24.
//  Copyright © 2017年 yq. All rights reserved.
//

import UIKit

class YQContactsViewController: UITableViewController,EMContactManagerDelegate{
   
    // 懒加载(好友列表)数据
    lazy var friends:NSMutableArray = {
        var error : EMError? = nil
        let buddyList  = EMClient.shared().contactManager.getContactsFromServerWithError(&error) as NSArray
        if (buddyList.count != 0) {
              print("获取服务器好友成功")
        }else {
            print("获取服务器好友失败-或者好友个数为0")
        }
        let friends = NSMutableArray(array: buddyList)
        return friends
    }()
    
    //MARK:- 系统回调
    override func viewDidLoad() {
        super.viewDidLoad()
     
        //设置代理
        tableView.dataSource = self
        tableView.delegate = self
        EMClient.shared().contactManager.add(self, delegateQueue: nil) // 要添加的代理为self

        self.tableView.rowHeight = 50
        self.tableView.separatorStyle = .none
    }
    
    override func viewWillAppear(_ animated: Bool) {
        
        self.tabBarController?.tabBar.isHidden = false
    }
    
    // 移除代理
    override func viewDidDisappear(_ animated: Bool) {
        super.viewDidAppear(animated)
        EMClient.shared().contactManager.removeDelegate(self)
   
    }
    
    // 按钮点击:添加好友
    @IBAction func addFriend(_ sender: Any) {
            print("click添加朋友")
       
        // 弹框UIAlertController
        let ac:UIAlertController = UIAlertController(title: "好友申请", message: nil, preferredStyle: UIAlertControllerStyle.alert)
       
        // textfield1
        ac.addTextField { (textField) in
            textField.placeholder = "填写userName"
        }
        
        // textfield2
        ac.addTextField { (textField) in
            textField.placeholder = "填写理由"
        }
       
        // 底部"发送"action按钮
        ac.addAction(UIAlertAction(title: "发送", style: UIAlertActionStyle.default, handler: { (action ) in
            let tf1 = ac.textFields?.first?.text
            let tf2 = ac.textFields?.last?.text
            // 环信添加好友的关键代码
            EMClient.shared().contactManager.addContact(tf1!, message:tf2! , completion: { (userName, error ) in
                if (error == nil) {
                    print("邀请为好友\(userName!)成功")
                }else {
                    print("取消添加好友,",error ?? "出错了")
                }
            })
        }))
        
        // 底部"取消"action按钮
       ac.addAction(UIAlertAction(title: "取消", style: UIAlertActionStyle.cancel, handler: { (action) in
           print("方法:  \(#function),行数:  \(#line)")
       }))
        
        // 屏幕弹出
        self.present(ac, animated: true, completion: nil)
    }
    
    // 好友处理我的请求返回的结果
    func friendRequestDidApprove(byUser aUsername: String!) {
        print("添加好友",aUsername,"成功")
    }
    
    func friendRequestDidDecline(byUser aUsername: String!) {
        print("加好友\(aUsername):的申请被拒绝了")
    }
}

//MARK:-数据源方法
extension YQContactsViewController {
    // 多少行
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.friends.count
    }
    // 每行显示什么内容
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
       
      let cell = YQContactCell.yq_cellWithTableView(tableView: tableView) as! YQContactCell
      cell.buddy = self.friends[indexPath.row] as? String
        
    return cell
    }
}

//MARK:-代理方法
extension YQContactsViewController {
    override func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {
     
        // 取出要删除的当前好友
        let deleteUserName = self.friends[indexPath.row] as! String
        // 删除
        let deleteRowAction = UITableViewRowAction(style: .default, title: "删除") { (rowAction, indexPath ) in
            // 删除当前联系人
            let error =  EMClient.shared().contactManager.deleteContact(deleteUserName , isDeleteConversation: true)
            if error == nil {
                print("删除联系人成功")
                // 删除成功之后,强制刷新好友列表
                self.friends.removeObject(at: indexPath.row)
                self.tableView.reloadData()
            }else{
                print("删除好友失败")
            }
        }
        
        // 标记为已读
        let tipReaded = UITableViewRowAction(style: .normal, title: "标记为已读") { (rowAction , indexPath ) in
            print("已经标记为已读")
        }
        return [deleteRowAction,tipReaded]
    }
    
    // 点击cell做什么操作
    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

        let detailVC = YQDetailUserInfoViewController.yq_detailUserInfoVc() as! YQDetailUserInfoViewController
        detailVC.buddy2 = self.friends[indexPath.row] as! String
        self.navigationController?.pushViewController(detailVC , animated: true)
      
    }
}
